package com.huitone.gddw.controller.monitoring.environment;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.common.ComConstant;
import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.dao.entity.ObjectDef;
import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.dto.monitoring.environment.EnvDTO;
import com.huitone.gddw.service.dto.monitoring.environment.RedisMonitorDTO;
import com.huitone.gddw.service.monitoring.base.IObjectDefService;
import com.huitone.gddw.service.monitoring.environment.IRedisMonitorService;

/**
 * redis监控
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="redisMon")
public class RedisMonitorController {

	private final static Logger LOGGER = Logger.getLogger(RedisMonitorController.class);
	
	@Autowired
	private IRedisMonitorService redisMonitorService;
	
	@Autowired
	private IObjectDefService objectDefService;
	
	/**
	 * 查询redis集群信息
	 * @param request
	 * @return Map<String, Object>
	 */
	@ResponseBody
	@RequestMapping(value="findRedisCluster")
	@Log(logType=LogType.SELECT, content="redis监控-查询redis集群信息")
	public Map<String, Object> findRedisCluster(HttpServletRequest request) {
		try {
			List<EnvDTO> result = redisMonitorService.findRedisCluster();
			
			Map<String, Object> map = new HashMap<>();
			for (EnvDTO envDTO : result) {
				map.put(envDTO.getKey(), envDTO);
			}
			return map;
		} catch (Exception e) {
			LOGGER.error("查询redis集群信息出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return null;
		}
	}
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	@Log(logType=LogType.SELECT, content="redis监控-查询redis监控列表")
	public QueryPage<RedisMonitorDTO> query(QueryPage<RedisMonitorDTO> page, HttpServletRequest request) {
		try {
			page.setParams(getParams(request));
			QueryPage<EnvDTO> result = redisMonitorService.selectPage(page);
			
			List<EnvDTO> l = result.getResult();
			List<RedisMonitorDTO> list = getList(l);
			
			QueryPage<RedisMonitorDTO> qp = new QueryPage<RedisMonitorDTO>();
			qp.setResult(list);
			qp.setPageNo(result.getPageNo());
			qp.setPageSize(result.getPageSize());
			qp.setTotalCount(result.getTotalCount());
			return qp;
		} catch (Exception e) {
			LOGGER.error("查询redis监控列表信息出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return null;
		}
	}
	
	/**
	 * 获取参数信息
	 * @param request
	 * @return Map<String, Object>
	 */
	private Map<String, Object> getParams(HttpServletRequest request) {
		String role = request.getParameter("role");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("role", role);
		return params;
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "redis监控列表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<EnvDTO> list = redisMonitorService.getRecord(params);
		List<RedisMonitorDTO> l = getList(list);
		if (null == l || 0 == l.size()) {
			l.add(new RedisMonitorDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, l).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	
	/**
	 * 封装数据
	 * @param l List<EnvDTO>
	 * @return List<RedisMonitorDTO>
	 */
	private List<RedisMonitorDTO> getList(List<EnvDTO> l) {
		List<RedisMonitorDTO> list = new ArrayList<>();
		for (EnvDTO envDTO : l) {
			boolean isSame = false;
			for (RedisMonitorDTO rm : list) {
				if (rm.getItemId().equals(envDTO.getItemId())) {
					rm.setValue(envDTO.getKey(), envDTO.getValue());
					isSame = true;
					break;
				}
			}
			if (!isSame) {
				RedisMonitorDTO rm = new RedisMonitorDTO();
				rm.setObjId(envDTO.getObjId());
				rm.setItemId(envDTO.getItemId());
				rm.setWarnCount(envDTO.getWarnCount());
				rm.setRecvMan(envDTO.getRecvMan());
				rm.setValue(envDTO.getKey(), envDTO.getValue());
				list.add(rm);
			}
		}
		return list;
	}
	
	/**
	 * 保存
	 * @param entity ObjectDef
	 * @param request
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	@Log(logType=LogType.SELECT, content="redis监控-添加redis")
	public Message save(ObjectDef entity, HttpServletRequest request) {
		try {
			entity.setObjType(ComConstant.RECUSE);
			objectDefService.save(entity);
			
			return new Message(true, "保存成功！");
		} catch (Exception e) {
			LOGGER.error("添加redis对象过程中出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return new Message(false, "保存失败！");
		}
	}
	
}
